package com.xintool.window.Buttons;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.Map;

//血量看个体
public class Button_kgt extends ButtonFactory {
    private static JFrame gtFrame;
    private JTextArea resultArea;
    private JComboBox<String> galaxyCombo;
    private JComboBox<String> planetCombo;
    private JsonObject jsonData;

    @Override
    public JButton showButton() {
        JButton button_xxl = ButtonFactory.getButton("个体查询");
        button_xxl.addActionListener(e -> {
            loadJsonData();  // 先加载数据
            createMainWindow();
        });
        return button_xxl;
    }

    // 加载JSON数据
    private void loadJsonData() {
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(
                        new FileInputStream(Paths.get("data", "chageti.txt").toFile()),
                        StandardCharsets.UTF_8))) { // 强制指定编码

            Gson gson = new Gson();
            jsonData = gson.fromJson(br, JsonObject.class);
        } catch (Exception e) {
            // 添加详细错误提示
            String errorMsg = "数据文件格式错误，请检查：\n"
                    + "1. 是否使用UTF-8编码\n"
                    + "2. 是否所有键名用双引号包裹\n"
                    + "3. 最后一个属性不能有逗号\n"
                    + "4. 必须使用半角符号\n"
                    + "原始错误信息：" + e.getMessage();
            JOptionPane.showMessageDialog(null, errorMsg);
        }
    }

    private void createMainWindow() {
        if (gtFrame != null) {
            gtFrame.toFront();
            return;
        }

        gtFrame = new JFrame("高个体查询");
        gtFrame.setSize(300, 350);
        gtFrame.setResizable(false);
        gtFrame.setLocationRelativeTo(null);
        gtFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        gtFrame.add(createMainPanel());
        gtFrame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                gtFrame = null;
                jsonData = null;
            }
        });
        gtFrame.setVisible(true);
    }

    private JPanel createMainPanel() {
        // 主面板使用边界布局
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 顶部选择面板（网格布局）
        JPanel selectPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST;

        // 第一行：星系选择
        gbc.gridy = 0;
        selectPanel.add(new JLabel("选择星系:"), gbc);
        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        galaxyCombo = new JComboBox<>();
        galaxyCombo.setPreferredSize(new Dimension(120, 28));
        if (jsonData != null) {
            // 添加所有星系选项
            jsonData.keySet().forEach(galaxyCombo::addItem);
        }
        selectPanel.add(galaxyCombo, gbc);

        // 第二行：星球选择
        gbc.gridy = 1;
        gbc.gridx = 0;
        selectPanel.add(new JLabel("选择星球:"), gbc);
        gbc.gridx = 1;
        planetCombo = new JComboBox<>();
        planetCombo.setPreferredSize(new Dimension(120, 28));
        if (jsonData.has("帕诺星系")) {
            galaxyCombo.setSelectedItem("帕诺星系");
            updatePlanetCombo("帕诺星系");
        }
        selectPanel.add(planetCombo, gbc);

        // 第三行：查询按钮
        // 设置GridBagLayout布局管理器中的gridy属性为2，表示组件位于第3行（行号从0开始计数）
        gbc.gridy = 2;
        // 设置GridBagLayout布局管理器中的gridx属性为0，表示组件位于第1列（列号从0开始计数）
        gbc.gridx = 0;
        // 设置GridBagLayout布局管理器中的gridwidth属性为2，表示组件的宽度跨越2列
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.CENTER;
        JButton searchBtn = new JButton("立即查询");
        // 设置搜索按钮的首选大小为宽120像素，高32像素
        searchBtn.setPreferredSize(new Dimension(120, 32));
        searchBtn.addActionListener(e -> displayResults());
        selectPanel.add(searchBtn, gbc);

        // 结果区域（带滚动条）
        resultArea = new JTextArea(5, 10);
        resultArea.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        // 设置resultArea组件的自动换行功能为true，使得文本在达到组件边界时自动换行
        resultArea.setLineWrap(true);
        // 设置resultArea组件的单词换行功能为true，使得文本在达到组件边界时按单词进行换行，避免单词被截断
        resultArea.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(resultArea);
        scrollPane.setBorder(BorderFactory.createTitledBorder("查询结果"));
        // 设置滚动条策略
        scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

        // 组合布局
        mainPanel.add(selectPanel, BorderLayout.NORTH);
        mainPanel.add(scrollPane, BorderLayout.CENTER);

        // 下拉框事件绑定
        galaxyCombo.addItemListener(e -> {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                updatePlanetCombo((String) e.getItem());
            }
        });

        return mainPanel;
    }

    // 更新星球下拉框
    private void updatePlanetCombo(String galaxy) {
        // 从名为 planetCombo 的组合框（ComboBox）中移除所有项目（Items）
        if(planetCombo!=null){
            planetCombo.removeAllItems();
        }
        if (jsonData != null && jsonData.has(galaxy)) {
            JsonObject planets = jsonData.getAsJsonObject(galaxy);
            for (String planet : planets.keySet()) {
                planetCombo.addItem(planet);
            }
        }
    }

    // 显示查询结果
    private void displayResults() {
        if (galaxyCombo.getSelectedItem() == null) {
            resultArea.setText("请先选择星系");
            return;
        }
        if (planetCombo.getSelectedItem() == null) {
            resultArea.setText("请先选择星球");
            return;
        }
        String selectedGalaxy = (String) galaxyCombo.getSelectedItem();
        String selectedPlanet = (String) planetCombo.getSelectedItem();

        if (selectedGalaxy == null || selectedPlanet == null) return;

        StringBuilder sb = new StringBuilder();
        try {
            JsonObject planetData = jsonData.getAsJsonObject(selectedGalaxy)
                    .getAsJsonObject(selectedPlanet);

            sb.append("   精灵\t等级-血量\n");
            for (Map.Entry<String, com.google.gson.JsonElement> entry : planetData.entrySet()) {
                String name = entry.getKey();
                String level = entry.getValue().getAsString();

                sb.append(String.format("   %s\t%s\n", name, level));
            }
        } catch (Exception e) {
            sb.append("数据解析错误");
        }

        resultArea.setText(sb.toString());
        resultArea.setCaretPosition(0); // 将文本光标定位到开头
        resultArea.scrollRectToVisible(new Rectangle(0, 0, 1, 1)); // 强制滚动到顶部
    }
}